package com.ruoyi.price.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.basic.domain.TbExchangeRate;
import com.ruoyi.basic.domain.TbMonthlyExchangeRate;
import com.ruoyi.basic.service.ITbExchangeRateService;
import com.ruoyi.basic.service.ITbMonthlyExchangeRateService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.BizExceptionEnum;
import com.ruoyi.common.enums.CurrenyType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.price.domain.TbProject;
import com.ruoyi.price.domain.dto.TbProjectDTO;
import com.ruoyi.price.mapper.TbProjectMapper;
import com.ruoyi.price.service.ITbProjectFormulaWidgetService;
import com.ruoyi.price.service.ITbProjectService;
import com.ruoyi.system.domain.SysFile;
import com.ruoyi.system.service.ISysFileService;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 工程信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-09-04
 */
@Service
public class TbProjectServiceImpl extends ServiceImpl<TbProjectMapper, TbProject> implements ITbProjectService
{
    @Autowired
    private ISysFileService fileService;
    @Autowired
    private ITbMonthlyExchangeRateService rateService;
    @Autowired
    private ITbMonthlyExchangeRateService monthlyExchangeRateService;
    @Autowired
    private ITbProjectFormulaWidgetService projectFormulaWidgetService;

    @Override
    public List<TbProject> listByCondition(TbProject tbProject, SysUser user) {
        List<TbProject> list = baseMapper.selectProjectList(tbProject);
        boolean admin = user.isAdmin();
        String loginName = user.getLoginName();
        list.forEach(item->{
            List<String> d = Lists.newArrayList();
            if(ObjectUtils.isNotEmpty(item.getProjectStartDate())){
                d.add(DateUtils.parseDateToStr("yyyy-MM-dd",item.getProjectStartDate()));
            }
            if(ObjectUtils.isNotEmpty(item.getProjectEndDate())){
                d.add(DateUtils.parseDateToStr("yyyy-MM-dd",item.getProjectEndDate()));
            }
            if(!d.isEmpty()){
                item.setProjectDate(d.stream().collect(Collectors.joining("~")));
            }
        });
        Iterator<TbProject> iterator = list.iterator();
        while (iterator.hasNext()) {
            TbProject item = iterator.next();
            if (admin) {
                // 管理员的话，移除暂存的且用户不是自己的
                if (!loginName.equals(item.getCreateBy()) && item.getStatus().equals("1")) {
                    iterator.remove();
                }
            } else {
                // 非管理员的话，移除用户不是自己的并且状态为暂存和保存的。
                if (!loginName.equals(item.getCreateBy())) {
                    if (item.getStatus().equals("1") || item.getStatus().equals("2")) {
                        iterator.remove();
                    }
                }
            }
        }
        return list;
    }

    @Override
    public boolean deleteByIds(String ids) {
        if(ObjectUtils.isEmpty(ids)){
            throw new ServiceException(BizExceptionEnum.REQUEST_PARAMETER_ERROR.getMessage());
        }
        LambdaQueryWrapper<TbProject> wrapper = new LambdaQueryWrapper();
        wrapper.in(TbProject::getId, Arrays.asList(ids.split(",")));
        return remove(wrapper);
    }

    @Override
    public TbProject getProjectById(Long id) {
        TbProject project = getById(id);
       /* if(ObjectUtils.isEmpty(project.getFileIds())){
            return project;
        }*/
       /* List<SysFile> files = fileService.listByIds(Arrays.asList(project.getFileIds().split(",")));
        project.setFiles(files);
        project.setFileJson(JSONUtil.toJsonStr(files));*/
        return project;
    }

    @Override
    public TbProject getNewProjectById(Long id) {
        TbProject project = getById(id);
       /* if(ObjectUtils.isEmpty(project.getFileIds())){
            return project;
        }*/
       /* List<SysFile> files = fileService.listByIds(Arrays.asList(project.getFileIds().split(",")));
        project.setFiles(files);
        project.setFileJson(JSONUtil.toJsonStr(files));*/
        return project;
    }

    @Override
    public int saveProject(TbProject tbProject) {
        check(tbProject);
        tbProject.setLaborRatio(tbProject.getLaborRatioStart()+":"+tbProject.getLaborRatioEnd());
        tbProject.setEfficiencyRatio(tbProject.getEfficiencyRatioStart()+":"+tbProject.getEfficiencyRatioEnd());
        return save(tbProject) ? 1 : 0;
    }

    @Override
    public int saveNewProject(TbProjectDTO projectDTO) {
        TbProject tbProject = new TbProject();
        BeanUtil.copyProperties(projectDTO,tbProject);
        tbProject.setId(null);
        check(tbProject);
        tbProject.setLaborRatio(tbProject.getLaborRatioStart()+":"+tbProject.getLaborRatioEnd());
        tbProject.setEfficiencyRatio(tbProject.getEfficiencyRatioStart()+":"+tbProject.getEfficiencyRatioEnd());
        // 保存关系表
        return save(tbProject) ? 1 : 0;
    }


    @Override
    public int updateProject(TbProject tbProject) {
        check(tbProject);
        tbProject.setLaborRatio(tbProject.getLaborRatioStart()+":"+tbProject.getLaborRatioEnd());
        tbProject.setEfficiencyRatio(tbProject.getEfficiencyRatioStart()+":"+tbProject.getEfficiencyRatioEnd());
        return updateById(tbProject) ? 1 : 0;
    }

    @Override
    public int updateNewProject(TbProject tbProject) {
        check(tbProject);
        tbProject.setLaborRatio(tbProject.getLaborRatioStart()+":"+tbProject.getLaborRatioEnd());
        tbProject.setEfficiencyRatio(tbProject.getEfficiencyRatioStart()+":"+tbProject.getEfficiencyRatioEnd());
        return updateById(tbProject) ? 1 : 0;
    }

    @Override
    public String cal(TbProject tbProject) {
        // 计算中外用工比
        // 中外用工比
        double chineseForeignRatio = NumberUtil.div(tbProject.getLaborRatioEnd(),tbProject.getLaborRatioStart()).doubleValue();
        // (中国工人工日单价+外国工人工日单价) * 1/中外用工比
        // 如果中国工人工日单价不为人民币需要转换
        if(!CurrenyType.CNY.getCode().equals(tbProject.getChineseWorkerUnitPriceType())){
            BigDecimal v = NumberUtil.mul(tbProject.getChineseWorkerUnitPrice(),tbProject.getChineseExchangeRateAmount());
            tbProject.setChineseWorkerUnitPrice(v);
        }
        // 如果外国工人工日单价不为人民币需要转换
        if(!CurrenyType.CNY.getCode().equals(tbProject.getForeignWorkerUnitPriceType())){
            BigDecimal v =  NumberUtil.mul(tbProject.getForeignWorkerUnitPrice(),tbProject.getForeignExchangeRateAmount());
            tbProject.setForeignWorkerUnitPrice(v);
        }

        double mul = NumberUtil.add(tbProject.getChineseWorkerUnitPrice(),NumberUtil.mul(tbProject.getForeignWorkerUnitPrice(), chineseForeignRatio)).doubleValue();
        // 计算中外功效比
        double efficiencyRatio = NumberUtil.div(tbProject.getEfficiencyRatioStart(),tbProject.getEfficiencyRatioEnd()).doubleValue();

        // 1+中外功效比/中外用工比
        double div = NumberUtil.add(1,NumberUtil.mul(efficiencyRatio,chineseForeignRatio));

        double v = NumberUtil.div(tbProject.getFixedUnitPrice(), tbProject.getActualUnitPrice()).doubleValue();

        double result = NumberUtil.mul(NumberUtil.div(mul, div), v);

        // 如果结算类型不为人民币计算结果需要转换
        if(!CurrenyType.CNY.getCode().equals(tbProject.getSettleCurrencyType())){
            BigDecimal rateAmount = tbProject.getForeignExchangeRateAmount();
            if(tbProject.getSettleCurrencyType().equals(tbProject.getChineseWorkerUnitPriceType())){
                rateAmount = tbProject.getChineseExchangeRateAmount();
            }
            result = NumberUtil.div(result,rateAmount).doubleValue();
        }

        return  NumberUtil.roundStr(result,2);
    }

    private void check(TbProject tbProject) {
        LambdaQueryWrapper<TbProject> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TbProject::getName, tbProject.getName())
                .apply(" date_format(project_start_date,'%Y-%m-%d') = {0} ", DateUtils.parseDateToStr("yyyy-MM-dd",tbProject.getProjectStartDate()))
                .apply(" date_format(project_end_date,'%Y-%m-%d') = {0} ", DateUtils.parseDateToStr("yyyy-MM-dd",tbProject.getProjectEndDate()))
                .orderByDesc(TbProject::getCreateTime);
        List<TbProject> list = list(wrapper);
        TbProject old = list.isEmpty() ? null : list.get(0);
        if (old != null && !old.getId().equals(tbProject.getId())) {
            throw new ServiceException("工程已存在");
        }
    }

    public static void main(String[] args) {
        String str = "1:2";
        System.out.println(str.substring(str.indexOf(":")+1,str.length()));
    }
}
